package com.hns.can.base.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hns.can.base.entity.BaseOrganEntity;
import com.hns.can.base.entity.SysRoleEntity;
import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.base.entity.SysUserRoleEntity;
import com.hns.can.base.vo.UserRoleVo;
import com.hns.frame.mybatis.Pagination;
import com.hns.frame.service.CommonService;
import com.hns.tool.pub.ContextHolderUtils;
import com.hns.tool.pub.DataConvertUtil;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.UtilString;

/**
 * 用户信息service
 * @author:zhangyu
 * @email:zhangyu2222z@sina.cn
 * @version Revision 2.0.0
 */
@Service
public class SysUserService extends CommonService{
    
	/**
	 * 根据ID获取角色表
	 * @param vo 用户角色参数
	 * @return 对应角色信息
	 * @author:zhangyu
	 * @email:zhangyu2222z@sina.cn
	 */
    public Pagination getPageRoleListByUserRoleVo(UserRoleVo vo) {
        Pagination page = this.myBatisPage("sysUser.getSysUserRoleCountByVo","sysUser.getSysUserRoleListByVo",vo,SysRoleEntity.class);
        return page;
    }
    
    /**
     * 获取用户未分配角色列表
     * @param vo 用户角色参数
     * @return 用户未分配角色列表
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    public Pagination getUnkownRoleListByUserRoleVo(UserRoleVo vo) {
        HttpServletRequest request = ContextHolderUtils.getRequest(); 
    	SysUserEntity curUser = (SysUserEntity) request.getSession().getAttribute("SES_CURRENTUSER");
    	Map<String,String> paramMap = new HashMap<String,String>();
    	paramMap.put("corpId", vo.getCorpId());
    	paramMap.put("userId", vo.getUserId());
    	paramMap.put("name", vo.getName());
    	paramMap.put("curUserId", curUser.getId());
        Pagination page = this.myBatisPage("sysUser.getUnkownSysUserRoleCountByVo","sysUser.getUnkownSysUserRoleListByVo",paramMap,SysRoleEntity.class);
        return page;
    }
    
    /**
     * 新增数据
     * @param entity 用户信息
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @Transactional
    public void saveSysUser(SysUserEntity entity) {
        entity.setId(UtilString.getUUID());
        //初始密码
        String repwd="123456";
        final Md5PasswordEncoder md5 = new Md5PasswordEncoder();
        md5.setEncodeHashAsBase64(false);
        String currentPwd = md5.encodePassword(repwd, PubUtil.filterNULL(entity.getAcctName()));
        entity.setStartDate("2015-01-01");
        entity.setEndDate("2999-12-31");
        entity.setPassword(currentPwd);
        entity.setCreateTs(new Date());
        commonEntityDao.save(entity);
    }
    
    /**
     * 修改数据
     * @param entity 用户信息
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @Transactional
    public void updateSysUser(SysUserEntity entity) {
        entity.setCreateTs(new Date());
        commonEntityDao.update(entity);
    }
    
    /**
     * 根据实体删除数据
     * @param entity 用户信息
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @Transactional
    public void deleteSysUser(SysUserEntity entity) {
        commonEntityDao.delete(entity);
    }
    
    /**
     * 批量删除用户
     * @param current_user_id 当前用户id
     * @param ids 用户id数组
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @SuppressWarnings({"unchecked", "rawtypes" })
    @Transactional
    public void deleteSysUserById(String[] ids) throws Exception {
        //删除用户信息
        commonEntityDao.delete(SysUserEntity.class, ids);
        //删除该用户角色关系
        SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
        sysUserRoleEntity.setUserId(ids[0]);
        Map map = DataConvertUtil.ConvertObjToMap(sysUserRoleEntity);
        commonEntityDao.deleteByParamsIgnoreNullValue(SysUserRoleEntity.class, map);
    }
    
    /**
     * 根据名称获取用户list
     * @param entity 查询参数
     * @return 用户信息list
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @SuppressWarnings({"unchecked"})
    public List<SysUserEntity> getSysUserListByName(SysUserEntity entity){
//        Map map = DataConvertUtil.ConvertObjToMap(entity);
//        return commonEntityDao.findByParamsIgnoreNullValue(SysUserEntity.class,map);
    	// 添加用户关联信息查询[所属企业、所属机构]
    	List<SysUserEntity> list = PubUtil.convertListMapToObject(sqlMapDao.selectList("sysUser.getSysUserListByName", entity), SysUserEntity.class);
        return list;
    }
    
    @SuppressWarnings({"unchecked"})
    public SysUserEntity getSysUserEntityByCheck(Map params){
        Map<String, Object> map = (Map<String, Object>) this.sqlMapDao.selectOne("sysUser.getSysUserListByName",params);
        SysUserEntity sysUserEntity = (SysUserEntity) PubUtil.convertMapToObject(map,SysUserEntity.class);
        return sysUserEntity;
    }
    
    /**
     * 获取所有用户
     * @return 用户list
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    public List<SysUserEntity> getSysUser() {
        return  commonEntityDao.findAll(SysUserEntity.class);
    }
    
    /**
     * 模糊查询用户组
     * @param acctName 查询关键字
     * @param corpId 公司id
     * @return 用户list
     * @throws QueryExprException
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @SuppressWarnings({"unchecked"})
    public List<SysUserEntity> getSysUserListByLike(String acctName,String corpId) throws Exception  {
        SysUserEntity entity= new SysUserEntity();
        entity.setAcctName(acctName);
        entity.setCorpId(corpId);
        List<SysUserEntity> list = PubUtil.convertListMapToObject(sqlMapDao.selectList("sysUser.getSysUserListByLike", entity), SysUserEntity.class);
        return list;
    }
    
    /**
     * 查询数据库是否有相同帐号
     * @param entity 用户实体
     * @return 相同账户数目
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    public int getSysUserByName(SysUserEntity entity) {
        int count = (Integer) sqlMapDao.selectOne("sysUser.getSysUserByName", entity);
        return count;
    }
    
    /**
     * 查询数据库是否有相同编码
     * @param entity 用户实体
     * @return 相同账户数目
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    public int getSysUserByCode(SysUserEntity entity) {
        int count = (Integer) sqlMapDao.selectOne("sysUser.getSysUserByCode", entity);
        return count;
    }
    /**
     * 编辑角色
     * @param entity 用户信息
     * @author:zhangyu 
     * @email:zhangyu2222z@sina.cn
     */
    @Transactional
    public void updateSysRole(SysUserEntity entity){
        SysUserEntity oldSysUserEntity = commonEntityDao.find(entity.getId(), SysUserEntity.class);
        String corpId = getCorpIdByOrganId(entity.getOrganId());
    	entity.setCorpId(corpId);
        //编辑角色信息
        entity.setCreateTs(oldSysUserEntity.getCreateTs());
        entity.setPassword(oldSysUserEntity.getPassword());
        commonEntityDao.update(entity);
    }
    
    /**
     * 删除指定用户对应的角色关系
     * @param id 用户id
     * @param roleIds 角色id
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @SuppressWarnings({"unchecked", "rawtypes" })
    @Transactional
    public void deleteUserRole(String id, String[] roleIds) {
        SysUserRoleEntity entity = new SysUserRoleEntity();
        entity.setUserId(id);
        for(String roleId:roleIds){
            entity.setRoleId(PubUtil.filterNULL(roleId));
            Map map = DataConvertUtil.ConvertObjToMap(entity);
            commonEntityDao.deleteByParamsIgnoreNullValue(SysUserRoleEntity.class, map);
        }
    }
    
    /**
     * 添加用户角色
     * @param userId 用户id
     * @param roleIds 角色id
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @Transactional
    public void saveUserRole(String userId, String[]  roleIds) {
        for(String roleId:roleIds){
            SysUserRoleEntity entity = new SysUserRoleEntity();
            //去空格 设置角色id
            entity.setRoleId(PubUtil.filterNULL(roleId));
            entity.setId(UtilString.getUUID());
            entity.setUserId(PubUtil.filterNULL(userId));
            entity.setCreateTs(new Date());
            commonEntityDao.save(entity);
        }
    }
    
    /**
     * 密码重置
     * @param entity 用户信息
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @Transactional
    public void resetPass(SysUserEntity entity) {
        //加密
        String repwd="123456";
        final Md5PasswordEncoder md5 = new Md5PasswordEncoder();
        md5.setEncodeHashAsBase64(false);
        String currentPwd = md5.encodePassword(repwd, PubUtil.filterNULL(entity.getAcctName()));
        entity.setPassword(currentPwd);
        entity.setCreateTs(new Date());
        commonEntityDao.update(entity);
    }
    
    /**
     * 验证密码
     * @param entity 用户信息
     * @return 符合信息的用户数目
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    public int findPassByName(SysUserEntity entity) {
        String repwd=entity.getPassword();
        final Md5PasswordEncoder md5 = new Md5PasswordEncoder();
        md5.setEncodeHashAsBase64(false);
        String currentPwd = md5.encodePassword(repwd, PubUtil.filterNULL(entity.getAcctName()));
        entity.setPassword(currentPwd);
        int count = (Integer) sqlMapDao.selectOne("sysUser.findPassByName",entity);
        return count;
    }
    
    /**
     * 更新密码
     * @param entity 用户信息
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @Transactional
    public void updatePass(SysUserEntity entity) {
        SysUserEntity sysUserEntity = commonEntityDao.find(entity.getId(), SysUserEntity.class);
        //加密
        String repwd=entity.getPassword();
        final Md5PasswordEncoder md5 = new Md5PasswordEncoder();
        md5.setEncodeHashAsBase64(false);
        String currentPwd = md5.encodePassword(repwd, PubUtil.filterNULL(entity.getAcctName()));
        sysUserEntity.setPassword(currentPwd);
        commonEntityDao.update(sysUserEntity);
    }
    
    /**
     * 查询用户
     * @param entity 查询参数
     * @return 用户信息
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @SuppressWarnings("unchecked")
    public SysUserEntity findSysUserByName(SysUserEntity entity){
        List<SysUserEntity> list = PubUtil.convertListMapToObject(sqlMapDao.selectList("sysUser.getSysUserList", entity), SysUserEntity.class);
        return list.get(0);
    }
    
    /**
     * 根据设备ID获取对应权限的用户列表
     * @param eqmtId 设备id
     * @return 用户list
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @SuppressWarnings("unchecked")
    public List<SysUserRoleEntity> getUserRoleByEqmtId(String eqmtId) {
        List<SysUserRoleEntity> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("sysUser.getUserRoleByEqmtId", eqmtId), SysUserRoleEntity.class);
        return list;
    }
    
    /**
     * 取得用户机构树
     * @param organId 机构id
     * @param userId 用户id
     * @return 用户机构树
     * @throws QueryExprException
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @SuppressWarnings({"unchecked"})
    public List<SysUserEntity> getSysUserTreeByOrgan(String organId, String userId) throws Exception  {
    	Map<String,String> paramMap = new HashMap<String,String>();
    	//modidy by qianjy 
    	//修改父节点为汉纳森的用户,替换为顶级节点,使得可以查看整棵树
    	if("11013b72246043cdb851389e56c4ef30".equals(organId.trim())
    			||"9a0abd85e067484b805ad9d6ffe3c3fe".equals(organId.trim())
    			||"d0139cf209bb4cce847271affa221718".equals(organId.trim())){
    		organId="07c81b83eb5e4786ba524c9c0f09c15f";
    	}
    	paramMap.put("organId", organId);
    	paramMap.put("userId", userId);
        List<SysUserEntity> list = PubUtil.convertListMapToObject(sqlMapDao.selectList("sysUser.getSysUserTreeByOrgan", paramMap), SysUserEntity.class);
        return list;
    }
    
    /**
     * 获取用户拥有的角色
     * @param userId 用户id
     * @return 用户对应的角色
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @Transactional
    public List<SysUserRoleEntity> getRoleIdsByUserId(String userId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        List<SysUserRoleEntity> list = commonEntityDao.findByParamsIgnoreNullValue(SysUserRoleEntity.class, map);
        return list;
    }
    
    /**
     * 获取机构所属公司id
     * @param organId
     * @return
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    private String getCorpIdByOrganId(String organId){
    	Map<String, Object> map = new HashMap<String, Object>();
        map.put("organId", organId);
        List<BaseOrganEntity> list = commonEntityDao.findByParamsIgnoreNullValue(BaseOrganEntity.class, map);
        return list.get(0).getCorpId();
    }
    
    /**
     * 更新密码
     * @param entity
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @Transactional
    public void commonUpdatePass(SysUserEntity entity) {
        SysUserEntity sysUserEntity = commonEntityDao.find(entity.getId(), SysUserEntity.class);
        //加密
        String repwd=entity.getPassword();
        final Md5PasswordEncoder md5 = new Md5PasswordEncoder();
        md5.setEncodeHashAsBase64(false);
        String currentPwd = md5.encodePassword(repwd, PubUtil.filterNULL(entity.getAcctName()));
        sysUserEntity.setPassword(currentPwd);
        commonEntityDao.update(sysUserEntity);
    }
    
    /**
     * 
     * @param id
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-6-10
     * @功能说明：密码重置
     */
    
    @Transactional
    public void commonResetPass(SysUserEntity entity) {
        //加密
        String repwd="123456";
        final Md5PasswordEncoder md5 = new Md5PasswordEncoder();
        md5.setEncodeHashAsBase64(false);
        String currentPwd = md5.encodePassword(repwd, PubUtil.filterNULL(entity.getAcctName()));
        entity.setPassword(currentPwd);
        entity.setCreateTs(new Date());
        commonEntityDao.update(entity);
    }
}
